package com.atguigu.spzx.manager.helper;

import com.atguigu.spzx.model.pojo.system.SysMenu;
import com.atguigu.spzx.model.vo.system.SysMenuVo;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @author dyl
 * @version 1.0
 * @description:
 * @date 2025/1/5 11:27
 */
public class MenuHelper {
    // 树化菜单
    public static List<SysMenu> menuToTree(List<SysMenu> menuList) {
        // 利用递归查找所有的子节点
        List<SysMenu> rootList = new ArrayList<>();
        for (SysMenu sysMenu : menuList) {
            if (sysMenu.getParentId() == 0) {
                findChildren(sysMenu, menuList);
                rootList.add(sysMenu);
            }
        }
        return rootList;
    }

    // 寻找子菜单
    private static void findChildren(SysMenu sysMenu, List<SysMenu> menuList) {
        for (SysMenu menu : menuList) {
            if (Objects.equals(menu.getParentId(), sysMenu.getId())) {
                if (sysMenu.getChildren() == null) {
                    sysMenu.setChildren(new ArrayList<>());
                }
                sysMenu.getChildren().add(menu);
                findChildren(menu, menuList);
            }
        }
    }

    // 树化菜单
    public static List<SysMenuVo> menuToVoTree(List<SysMenu> menuList) {
        // 利用递归查找所有的子节点
        List<SysMenuVo> rootList = new ArrayList<>();
        for (SysMenu sysMenu : menuList) {
            SysMenuVo sysMenuVo = new SysMenuVo();
            if (sysMenu.getParentId() == 0) {
                findChildrenVo(sysMenu, sysMenuVo, menuList);
                sysMenuVo.setName(sysMenu.getComponent());
                sysMenuVo.setTitle(sysMenu.getTitle());
                rootList.add(sysMenuVo);
            }
        }
        return rootList;
    }

    // 寻找子菜单
    private static void findChildrenVo(SysMenu sysMenu, SysMenuVo sysMenuVo, List<SysMenu> menuList) {
        for (SysMenu menu : menuList) {
            SysMenuVo vo = new SysMenuVo();
            if (Objects.equals(menu.getParentId(), sysMenu.getId())) {
                if (sysMenu.getChildren() == null) {
                    sysMenu.setChildren(new ArrayList<>());
                    sysMenuVo.setChildren(new ArrayList<>());
                }
                vo.setTitle(menu.getTitle());
                vo.setName(menu.getComponent());
                sysMenuVo.getChildren().add(vo);
                sysMenu.getChildren().add(menu);
                findChildrenVo(menu, vo, menuList);
            }
        }
    }
}
